<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showNotify } from 'vant'
import { getAllMaterielRegulationData } from '@/api/Base/product'

interface TreeNode {
  id: number
  label: string
  children?: TreeNode[]
}

const componentTree = ref<TreeNode[]>([])
const productClass = defineModel<TreeNode[]>("productClass", { default: [] })

onMounted(() => {
  getAllMaterielRegulationData({}).then(res => {
    if (res.code === 0) {
      componentTree.value = res.data
    } else {
      showNotify({ type: 'danger', message: res.msg })
    }
  })
})

const props = defineProps<{
  levels: number
}>()

const selectedValues = ref<number[]>(Array(props.levels).fill(0))
const showPicker = ref<boolean[]>(Array(props.levels).fill(false))
const searchQueries = ref<string[]>(Array(props.levels).fill(''))
const filteredOptions = ref<Array<Array<{ text: string; value: number }>>>(Array(props.levels).fill([]))

function getSelectedText(level: number): string {
  const id = selectedValues.value[level]
  if (!id) return ''
  
  if (level === 0) {
    const node = componentTree.value.find(n => n.id === id)
    return node?.label || ''
  }
  
  const parentId = selectedValues.value[level - 1]
  const parentNode = componentTree.value.find(n => n.id === parentId)
  if (!parentNode?.children) return ''
  
  const childNode = parentNode.children.find(n => n.id === id)
  return childNode?.label || ''
}

function handleSearch(query: string, level: number) {
  searchQueries.value[level] = query
  
  if (!query) {
    filteredOptions.value[level] = []
    return
  }

  if (level === 0) {
    filteredOptions.value[level] = componentTree.value
      .filter(node => node.label.includes(query))
      .map(node => ({
        text: node.label,
        value: node.id
      }))
    return
  }

  const parentId = selectedValues.value[level - 1]
  const parentNode = componentTree.value.find(n => n.id === parentId)
  
  if (parentNode?.children) {
    filteredOptions.value[level] = parentNode.children
      .filter(node => node.label.includes(query))
      .map(node => ({
        text: node.label,
        value: node.id
      }))
  }
}

function getOptions(level: number): Array<{ text: string; value: number }> {
  if (searchQueries.value[level]) {
    return filteredOptions.value[level]
  }

  if (level === 0) {
    return componentTree.value.map(node => ({
      text: node.label,
      value: node.id
    }))
  }

  const parentId = selectedValues.value[level - 1]
  const parentNode = componentTree.value.find(n => n.id === parentId)
  
  if (!parentNode?.children) {
    return []
  }

  return parentNode.children.map(node => ({
    text: node.label,
    value: node.id
  }))
}

interface PickerConfirmValue {
  selectedValues: number[]
  selectedOptions: Array<{ text: string; value: number }>
}

function onConfirm(level: number, value: unknown) {
  if (!value || typeof value !== 'object' || !('selectedValues' in value)) {
    return
  }
  
  const { selectedValues } = value as PickerConfirmValue
  const selectedValue = selectedValues[0]
  
  if (selectedValue) {
    handleSelect(level, selectedValue)
    showPicker.value[level] = false
  }
}

function handleSelect(level: number, value: number) {
  selectedValues.value[level] = value
  // 清空后续级别的选择
  for (let i = level + 1; i < selectedValues.value.length; i++) {
    selectedValues.value[i] = 0
  }
  
  // 批量更新productClass
  const selectedNodes: TreeNode[] = []
  let currentTree = componentTree.value
  
  for (let i = 0; i <= level; i++) {
    const id = selectedValues.value[i]
    if (!id) break
    
    const node = currentTree.find(n => n.id === id)
    if (!node) break
    
    selectedNodes.push({
      id: node.id,
      label: node.label
    })
    
    if (node.children) {
      currentTree = node.children
    }
  }
  
  productClass.value = selectedNodes
}

defineExpose({
  selectedValues,
  handleSearch
})
</script>

<template>
  <div class="component-selector">
    <div v-for="(_, index) in levels" :key="index" class="level">
      <van-field
        :model-value="selectedValues[index] ? getSelectedText(index) : ''"
        :label="`第 ${index + 1}大类`"
        placeholder="请选择"
        readonly
        @click="showPicker[index] = true"
      />
      <van-popup v-model:show="showPicker[index]" position="bottom">
        <van-search
          v-model="searchQueries[index]"
          :placeholder="`搜索级别 ${index + 1} 选项`"
          @update:model-value="(val: string) => handleSearch(val, index)"
        />
        <van-picker
          :columns="[getOptions(index)]"
          @confirm="(value) => onConfirm(index, value)"
          @cancel="() => {
            showPicker[index] = false
            searchQueries[index] = ''
          }"
        />
      </van-popup>
    </div>
  </div>
</template>

<style lang="less" scoped>
.component-selector {
  .level {
    margin-bottom: 12px;
  }
}
</style>
